package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.engine.GroovyScriptEngine;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.extend.service.ExtendScriptImpl;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil.ReturnType;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdChemicalPhysicsInfo;
import com.ccp.dev.qbdms.model.WQbdFlightTest;
import com.ccp.dev.qbdms.model.WQbdXhdh;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.system.service.DictionaryService;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Objects;
import net.sf.json.JSONObject;
import java.nio.charset.StandardCharsets;
import com.ccp.dev.qbdms.model.WQbdPressureElementInfo;
import com.ccp.dev.qbdms.service.WQbdPressureElementInfoService;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.poi.excel.editor.IFontEditor;
import com.ccp.dev.core.poi.excel.style.Color;
import com.ccp.dev.core.poi.excel.style.DataFormat;
import com.ccp.dev.core.poi.excel.style.font.BoldWeight;
import com.ccp.dev.core.poi.excel.style.font.Font;
import com.ccp.dev.core.poi.excel.util.ExcelUtil;
import java.util.ArrayList;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 压力元件 信息操作处理控制器
 *
 * @author milihao
 * @date 2020-07-06 09:24:07
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "压力元件")
@RequestMapping("/qbdms/wQbdPressureElementInfo")
public class WQbdPressureElementInfoController extends SysBaseController {

	@Resource
	private WQbdPressureElementInfoService wQbdPressureElementInfoService;
	@Resource
	private DictionaryService dictionaryService;
	@Resource
	private WCustomColumnsService wCustomColumnsService;
	@Resource
	private GroovyScriptEngine engine;
	@Resource
	private ExtendScriptImpl extendScriptImpl;
	/**
	 * 功能描述: 跳转到首页
	 *
	 * @return: java.lang.String
	 * @auther: milihao
	 * @date: 2020-07-06 09:24:07
	 */
	@RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
	@Action(description = "跳转到压力元件首页", exectype = "页面跳转日志")
	public String viewList(ModelMap modelMap, HttpServletRequest request) {
		modelMap.put("currentSystemLevel", BaseUtil.getCurrentSystemLevel());
		modelMap.put("userId", ContextUtil.getCurrentUserId());
		wCustomColumnsService.addCustomCols(request);
		return "wQbdPressureElementInfo/list";
	}

	/**
	 * 功能描述: 附带检索条件的分页查询
	 *
	 * @param: [request] http请求
	 * @return: java.lang.Object
	 * @auther: milihao
	 * @date: 2020-07-06 09:24:07
	 */
	@RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
	@ResponseBody
	@Action(description = "附带检索条件的分页查询压力元件", detail = "查询数据信息<#if success>成功<#else></#if>")
	public Object list(HttpServletRequest request) {
		QueryFilter queryFilter = new QueryFilter(request, true);
		//分页数据
		ZhiLiangConst.addQueryFilter(queryFilter);
		List<WQbdPressureElementInfo> pageDatas = wQbdPressureElementInfoService.queryList(queryFilter);
		for (WQbdPressureElementInfo pageData : pageDatas) {
			try {
				pageData.setReportStatusStr(ZhiLiangConst.getStatusStrByInt(pageData.getReportStatus()));
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		try {
			ZhiLiangConst.showName(pageDatas);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		ZhiLiangConst.isDataAllowEdit(pageDatas, false);
		SysAuditThreadLocalHolder.putParamerter("success", true);
		return success(pageDatas, queryFilter.getPageBean().getTotalCount());
	}

	/**
	 * 功能描述: 附带检索条件的分页查询
	 *
	 * @param: [request] http请求
	 * @return: java.lang.Object
	 * @auther: milihao
	 * @date: 2020-07-06 09:24:07
	 */
	@RequestMapping("/reportList")
	@ResponseBody
	@Action(description = "附带检索条件的分页查询压力元件(上报)", detail = "查询数据信息<#if success>成功<#else></#if>")
	public Object reportList(HttpServletRequest request, @RequestParam("id") String id,
			@RequestParam("tableName") String tableName) {
		List<WQbdPressureElementInfo> wQbdPressureElementInfoReportList = wQbdPressureElementInfoService
				.reportList(id, tableName);
		SysAuditThreadLocalHolder.putParamerter("success", true);
		return getResultDataSuccess("options.success", wQbdPressureElementInfoReportList);

	}

	/**
	 * 功能描述: 跳转到新增页面
	 *
	 * @return: java.lang.String
	 * @auther: milihao
	 * @date: 2020-07-06 09:24:07
	 */
	@RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
	@Action(description = "跳转到压力元件新增页面", exectype = "页面跳转日志")
	public String viewAdd(HttpServletRequest request, ModelMap modelMap) {
		String id = RequestUtil.getString(request, "id");
		modelMap.put("id", id);
		return "wQbdPressureElementInfo/add";
	}

	/**
	 * 功能描述:  数据保存通用方法
	 *
	 * @param: wQbdPressureElementInfo 保存的对象
	 * @return: java.lang.Object
	 * @auther: milihao
	 * @date: 2020-07-06 09:24:07
	 */
	@RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
	@ResponseBody
	@Action(description = "保存压力元件数据", detail = "<#if isAdd>新增<#else>编辑</#if>压力元件数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
	public Object save(@RequestBody WQbdPressureElementInfo wQbdPressureElementInfo) {
		String id = wQbdPressureElementInfo.getId();
		int result;
		if (StringUtil.isEmpty(id)) {
			SysAuditThreadLocalHolder.putParamerter("isAdd", true);
			//新增操作
			//新增数据前生成随机Id
			wQbdPressureElementInfo.setId(ProjectUUIDUtils.getUUIDFor32());
			ZhiLiangConst.addCommonFields(wQbdPressureElementInfo);
			wQbdPressureElementInfo.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
			result = wQbdPressureElementInfoService.add(wQbdPressureElementInfo);
		} else {
			SysAuditThreadLocalHolder.putParamerter("success", false);
			//修改操作
			WQbdPressureElementInfo oldwQbdPressureElementInfo = wQbdPressureElementInfoService
					.getOneById(id);
			String modifyInfo = StructureModifyUtil
					.getModifyInfo(oldwQbdPressureElementInfo, wQbdPressureElementInfo);
			SysAuditThreadLocalHolder.putParamerter("modifyInfo", modifyInfo);
			ZhiLiangConst.updateCommonFields(wQbdPressureElementInfo);
			result = wQbdPressureElementInfoService.update(wQbdPressureElementInfo);
		}
		if (result > 0) {
			SysAuditThreadLocalHolder.putParamerter("success", true);
		} else {
			SysAuditThreadLocalHolder.putParamerter("success", false);
		}
		return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
	}

	/**
	 * 功能描述: 跳转到详情页面
	 *
	 * @return: java.lang.String
	 * @auther: milihao
	 * @date: 2020-07-06 09:24:07
	 */
	@RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
	@Action(description = "跳转到压力元件详情页面", exectype = "页面跳转日志")
	public String viewParticulars(HttpServletRequest request, ModelMap modelMap) {
		String id = RequestUtil.getString(request, "id");
		String isClose = RequestUtil.getString(request, "isClose");
		modelMap.put("id", id);
		modelMap.put("isClose", isClose);
		return "wQbdPressureElementInfo/particulars";
	}

	/**
	 * 功能描述: 根据主键id获取一条数据的通用查询方法
	 *
	 * @param: id 参数对象必须是"id"
	 * @return: java.lang.Object
	 * @auther: milihao
	 * @date: 2020-07-06 09:24:07
	 */
	@RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
	@ResponseBody
	@Action(description = "根据主键id查询压力元件的一条数据", detail = "根据主键id查询压力元件的数据<#if success>成功<#else>失败</#if>")
	public Object get(@RequestParam("id") String id) {
		WQbdPressureElementInfo wQbdPressureElementInfo = wQbdPressureElementInfoService.getOneById(id);
		if (null == wQbdPressureElementInfo) {
			SysAuditThreadLocalHolder.putParamerter("success", false);
			return getResultDataError("get.failure");
		}
		SysAuditThreadLocalHolder.putParamerter("success", true);
		return getResultDataSuccess("get.success", wQbdPressureElementInfo);
	}

	/**
	 * 功能描述: 根据主键ID删除数据的通用删除方法
	 *
	 * @param: id 参数名称必须是"id"
	 * @return: java.lang.Object
	 * @auther: milihao
	 * @date: 2020-07-06 09:24:07
	 */
	@PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
	@ResponseBody
	@Action(description = "根据主键ID删除压力元件数据", exectype = "删除日志", detail = "删除数据信息<#if success>成功<#else>失败</#if>")
	public Object delete(@RequestParam("id") String id) {
		if (StringUtil.isEmpty(id)) {
			SysAuditThreadLocalHolder.putParamerter("success", false);
			return fail("delete.failure.message");
		}
		String userId = ContextUtil.getCurrentUserId();
		String[] ids = id.split(",");
		for (String key : ids) {
			WQbdPressureElementInfo data = wQbdPressureElementInfoService.getOneById(key);
			if (Objects.nonNull(data.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED
					.equals(data.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED
					.equals(data.getReportStatus())) {
				SysAuditThreadLocalHolder.putParamerter("success", false);
				return fail("删除失败，只允许删除待上报和待报集团的数据");
			}
			if (!userId.equals(data.getCreateBy())) {
				SysAuditThreadLocalHolder.putParamerter("success", false);
				return fail("删除失败，只能删除自己创建的数据！");
			}
		}
		int result = wQbdPressureElementInfoService.delByIdArray(id.split(","));
		if (result > 0) {
			SysAuditThreadLocalHolder.putParamerter("success", true);
		} else {
			SysAuditThreadLocalHolder.putParamerter("success", false);
		}
		return result > 0 ? getResultDataSuccess("delete.success")
				: getResultDataError("delete.failure");
	}

	/**
	 * 功能描述: 跳转到导入页面
	 *
	 * @return: java.lang.String
	 * @auther: hw
	 * @date: 2019-12-25 19:21:40
	 */
	@RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
	@Action(description = "跳转到压力元件导入页面", exectype = "页面跳转日志")
	public String viewImport() {
		return "wQbdPressureElementInfo/import";
	}

	/**
	 * 功能描述: 跳转到导出选择字段页面
	 */
	@RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
	@Action(description = "跳转到压力元件导出选择字段页面", exectype = "页面跳转日志")
	public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
		com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil
				.resolverModel(WQbdPressureElementInfo.class);
		modelMap.put("tableInfo", jsonObject.toString());
		return "expImp/add";
	}

	/**
	 * 功能描述: 导出飞压力元件数据信息
	 *
	 * @param: [request] http请求
	 * @return: java.lang.Object
	 * @auther: hjx
	 * @date: 2020-05-07 15:28:26
	 */
	@RequestMapping("/exportData")
	@Action(description = "导出压力元件数据信息", detail = "导出压力元件数据信息<#if success>成功<#else></#if>")
	public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysAuditThreadLocalHolder.putParamerter("success", false);
		String[] id = RequestUtil.getStringAryByStr(request, "id");
		QueryFilter queryFilter = new QueryFilter(request, false);
		JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
		List<WQbdPressureElementInfo> WQbdPressureElementInfos = this.wQbdPressureElementInfoService
				.queryAll(queryFilter);
		if (WQbdPressureElementInfos.isEmpty()) {
			WQbdPressureElementInfos.add(new WQbdPressureElementInfo());
		}
		new AbstractExpUtil() {
			@Override
			public String customAnalysis(String fieldName, String fieldValue) {
				return null;
			}
		}.executeExport(request, response, WQbdPressureElementInfos, dataArray,
				AbstractExpUtil.ExpStyle.MANY_SHEET);
		SysAuditThreadLocalHolder.putParamerter("success", true);
	}

	/**
	 * 导入资源文件
	 */
	@RequestMapping("/importData")
	@ResponseBody
	public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response)
			throws Exception {
		SysAuditThreadLocalHolder.putParamerter("success", false);
		MultipartFile multipartFile = request.getFile("file");
		TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
		List<Dictionary> qylbList = dictionaryService.getByNodeKey("qylb");
		List<Dictionary> yjlbList = dictionaryService.getByNodeKey("yjlb");
		Map<String, Object> map = new AbstractImpUtil() {
			@Override
			public ReturnType customValidation(String fieldName, String fieldValue) {
				ReturnType returnType = null;
				if ("batchNumber".equals(fieldName)) {
					returnType = new AbstractImpUtil.ReturnType();
					boolean sign = true;
					try {
						Integer.parseInt(fieldValue.replace(",",""));
						returnType.setNewValue(fieldValue.replace(",",""));
						sign = false;
					} catch (Throwable t) {
					}
					if (sign) {
						returnType.setMsg("非法的值!");
					}
				} else if ("componentCategory".equals(fieldName)) {
					returnType = new AbstractImpUtil.ReturnType();
					boolean sign = true;
					for (Dictionary dictionary : yjlbList) {
						if (dictionary.getItemName().equals(fieldValue)) {
							returnType.setNewValue(dictionary.getItemValue());
							sign = false;
							break;
						}
					}
					if (sign) {
						returnType.setMsg("非法的值!");
					}
				} else if ("businessCategory".equals(fieldName)) {
					returnType = new AbstractImpUtil.ReturnType();
					boolean sign = true;
					for (Dictionary dictionary : qylbList) {
						if (dictionary.getItemName().equals(fieldValue)) {
							returnType.setNewValue(dictionary.getItemValue());
							sign = false;
							break;
						}
					}
					if (sign) {
						returnType.setMsg("非法的值!");
					}
				}
				return returnType;
			}
		}.reverseModels(excelEntity, WQbdPressureElementInfo.class);
		String msg = map.get("msg").toString();
		List<WQbdPressureElementInfo> list = (List<WQbdPressureElementInfo>) map.get("instList");
		if (StringUtil.isEmpty(msg)) {
			this.wQbdPressureElementInfoService.addImportData(list);
			SysAuditThreadLocalHolder.putParamerter("success", true);
			return getResultDataSuccess("dataSource.importXml.success");
		} else {
			SysAuditThreadLocalHolder.putParamerter("success", false);
			return fail(msg);
		}
	}


}
